package com.qth.valet.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qth.valet.common.annotation.Logs;
import com.qth.valet.common.annotation.RepeatSubmit;
import com.qth.valet.common.theadlocal.UserOrDriverIdHolder;
import com.qth.valet.common.utils.ResponseResult;
import com.qth.valet.common.utils.StatusConstants;
import com.qth.valet.common.utils.ToolUtils;
import com.qth.valet.entity.po.KmPrice;
import com.qth.valet.entity.po.Orders;
import com.qth.valet.entity.req.DriverFinishOrderReq;
import com.qth.valet.entity.vo.OrdersDetail;
import com.qth.valet.service.KmPriceService;
import com.qth.valet.service.OrderHistoryService;
import com.qth.valet.service.OrdersService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/qth/order")
@RequiredArgsConstructor
public class OrdersController {

    private final OrdersService ordersService;

    private final OrderHistoryService orderHistoryService;

    private final KmPriceService kmPriceService;

    @Value("${order.maxdistance}")
    private int maxdistance;



    @Logs(operation = "创建订单")
    @PostMapping("/save")
    @RepeatSubmit
    public ResponseResult<Orders> saveOrder(@RequestBody Orders orders){
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, orders.getUserId())
                .ne(Orders::getStatus, StatusConstants.ORDER_FINISH)
                .ne(Orders::getStatus, StatusConstants.ORDER_CANCEL)
                .ne(Orders::getStatus, StatusConstants.ORDER_REFUND_PENDING)
                .ne(Orders::getStatus, StatusConstants.ORDER_REFUNDED)
                .ne(Orders::getStatus, StatusConstants.ORDER_REFUND_REFUSED);
        List<Orders> inProgress = ordersService.list(queryWrapper);

        if(!inProgress.isEmpty()){
            return ResponseResult.fail(444, "有未完成的订单", inProgress.get(0));
        }

        orders.setId(ToolUtils.generateOrder());
        orders.setOrderTime(new Date());
        ordersService.save(orders);

        orderHistoryService.saveOrderHistory(orders.getId(), orders.getUserId(), null, "用户创建订单");

        ordersService.publishOrder(orders);

        return ResponseResult.success(orders);
    }

    //@Logs(operation = "用户正在执行的订单")
    @GetMapping("/inProgress")
    public ResponseResult<Orders> inProgress(){
        List<Integer> statuses = Arrays.asList(StatusConstants.ORDER_WAIT, StatusConstants.ORDER_GET, StatusConstants.ORDER_DRIVER_WAIT,
                StatusConstants.ORDER_START, StatusConstants.ORDER_PENDING_PAY);
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<Orders>()
                .eq(Orders::getUserId, UserOrDriverIdHolder.getUserId())
                .in(Orders::getStatus, statuses)
                .last("limit 1");
        Orders inProgress = ordersService.getOne(lambdaQueryWrapper);
        return ResponseResult.success(inProgress);
    }

    //@Logs(operation = "通过用户id查询订单")
    @GetMapping("/list")
    public ResponseResult<IPage<Orders>> list(@RequestParam(defaultValue = "1") int pageNum,
                               @RequestParam(defaultValue = "10") int pageSize){
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, UserOrDriverIdHolder.getUserId());
        queryWrapper.orderByDesc(Orders::getId);
        //List<Orders> list = ordersService.list(queryWrapper);
        Page<Orders> page = new Page<>(pageNum, pageSize);

        IPage<Orders> ordersPage = ordersService.getBaseMapper().selectPage(page, queryWrapper);

        return ResponseResult.success(ordersPage);
    }

    //@Logs(operation = "订单详情")
    @GetMapping("/detail")
    public ResponseResult<OrdersDetail> detail(String orderId){
        OrdersDetail orderDetail = ordersService.getOrderDetail(orderId);
        return ResponseResult.success(orderDetail);
    }

    @Logs(operation = "更新订单状态")
    @PostMapping("/updateSts")  // 司机完成订单的操作不再调用此接口，而是调用下面的接口
    public ResponseResult<Void> updateSts(@RequestBody Orders orders){
        return ordersService.updateOrderSts(orders);
    }

    @Logs(operation = "司机完成订单")
    @PostMapping("/driver_finish_order")
    public ResponseResult<Void> driverFinishOrder(@RequestBody @Valid DriverFinishOrderReq req){
        ordersService.driverFinishOrder(req);
        return ResponseResult.success();
    }

    //@Logs(operation = "根据id获取订单")
    @GetMapping("/getById")
    public ResponseResult<Orders> getById(String orderId){
        Orders one = ordersService.getOrderById(orderId);
        if(one == null){
            return ResponseResult.fail("找不到订单，请重试");
        }
        return ResponseResult.success(one);
    }

    @GetMapping("/getPrice")
    public ResponseResult<Integer> getPrice(Integer km){
        KmPrice price = kmPriceService.getById(km);
        boolean withinRange = ToolUtils.isWithinRange();
        if(price != null && km < maxdistance){
            Integer total = withinRange ? price.getDayPrice() : price.getNightPrice();
            return ResponseResult.success(total);
        }
        return ResponseResult.fail("距离不能超过200公里，请重新选择");
    }

     /*
     * 根据司机id查询是否有订单正在服务
     */
    @GetMapping("checkDriverOrder")
    public ResponseResult<Integer> checkDriverOnline(Integer driverId){
        List<Orders> orders = ordersService.checkDriverOnline(driverId);
        return ResponseResult.success(orders.size());
    }

    /*
     * 司机创建订单
     */
    @Logs(operation = "司机端创建订单")
    @PostMapping("driverCreate")
    @RepeatSubmit //防止司机重复提交请求
    public ResponseResult<Orders> driverCreatOrder(@RequestBody Orders orders){
        List<Orders> inProgressOrders =  ordersService.checkDriverOnline(orders.getDriverId());
        if(!inProgressOrders.isEmpty()){
            return ResponseResult.fail("您有进行中的订单，请完成后再次创建");
        }

        orders.setId(ToolUtils.generateOrder());
        orders.setOrderTime(new Date());
        orders.setStatus(StatusConstants.ORDER_GET);

        // 保存到数据库
        ordersService.save(orders);

        // 记录历史订单
        orderHistoryService.saveOrderHistory(orders.getId(),null, orders.getDriverId(),"司机创建订单");

        return ResponseResult.success(orders);
    }
}
